package lv.webkursi.web2007a.sem06.upload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class UploadToBytesController extends SimpleFormController {

	Log log = LogFactory.getLog(UploadToBytesController.class);

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {

		// cast the bean
		UploadToBytesBean bean = (UploadToBytesBean) command;

		// let's see if there's content there
		byte[] file = bean.getContent();
		if (file == null) {
			log.warn("The user did not upload anything");
		} else {
			// TODO Do something with the uploaded file
		}

		return super.onSubmit(request, response, command, errors);
	}

	@Override
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws ServletException {
		binder.registerCustomEditor(byte[].class,
				new ByteArrayMultipartFileEditor());
	}
}
